<template>
  <div class="container">
    <el-row>
      <el-col style="text-align: right">
        <el-date-picker
          v-model="addQuery.dt"
          :picker-options="pickerOptions"
          type="date"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
        <label for="">平台</label>
        <el-select v-model="addQuery.platform" size="small" class="w-140">
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label for="">崩溃数</label>
        <el-input
          v-model="addQuery.collapseCount"
          size="small"
          class="w-140"
          oninput="value=value.replace(/[^\d]/g,'')"
          clearable
        />
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="add()"
        >添加</el-button
        >
      </el-col>
      <el-col style="text-align: right" class="p-t-15">
        <el-date-picker
          v-model="datePicker"
          :picker-options="pickerOptions"
          type="daterange"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="search()"
        >搜索</el-button
        >
      </el-col>
    </el-row>

    <!-- Android -->
    <el-row class="p-t-15">
      <el-col>
        <el-tabs ref="tabs" v-model="activaNameArr[0]" type="card">
          <el-tab-pane label="Android" name="first">
            <div class="echart">
              <div
                id="echartsOne"
                :style="{ width: '100%', height: '480px' }"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <div
      class="dividing-line"
      style="margin: 10px 0; border: 1px solid #e6e6e6"
    />

    <!-- IOS -->
    <el-row class="p-t-15">
      <el-col>
        <el-tabs ref="tabs" v-model="activaNameArr[1]" type="card">
          <el-tab-pane label="IOS" name="first">
            <div class="echart">
              <div
                id="echartsTwo"
                :style="{ width: '100%', height: '480px' }"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import echarts from 'echarts';
import { dateShortcutKeyJS } from '@/mixins/index.js';
import timeUtils from '@/utils/timeHandle.js';
import {
  addCollapseApi,
  getActiveCollapseListApi
} from '@/api/online-quality.js';
const domMap = {
  0: 'echartsOne',
  1: 'echartsTwo'
};
export default {
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      domMap,
      options1: [
        {
          value: 1,
          label: 'Android'
        },
        {
          value: 2,
          label: 'IOS'
        }
      ],
      addQuery: {
        dt: timeUtils.timeHandle(new Date().getTime(), 'date'),
        platform: 1,
        collapseCount: null
      },
      datePicker: [
        timeUtils.timeHandle(
          new Date(new Date().getTime() - 7 * 24 * 3600000).getTime(),
          'date'
        ),
        timeUtils.timeHandle(new Date().getTime() - 1 * 24 * 3600000, 'date')
      ],

      activaNameArr: ['first', 'first'],
      listQuery: {
        startTime: null,
        endTime: null
      },
      list: [{}, {}]
    };
  },

  mounted() {
    this.search();
  },

  methods: {
    async add() {
      const { dt, collapseCount } = this.addQuery;
      if (dt == null) {
        this.$message.warning('请选择崩溃时间', true);
        return;
      }

      if (!collapseCount || collapseCount <= 0) {
        this.$message.warning('崩溃数必须为正整数', true);
        return;
      }

      try {
        const { code } = await addCollapseApi({ ...this.addQuery, collapseCount: Number(collapseCount) });
        if (code == 200) {
          this.$message.success('添加成功', true);
          this.search();
        } else {
          this.$message.warning('添加崩溃数失败，请重试', true);
        }
      } catch (error) {
        console.log(error);
      }
    },

    search() {
      const { datePicker, listQuery } = this;
      if (!datePicker) {
        this.$message.warning('请输入搜索时间', true);
        return;
      }

      listQuery.startTime = datePicker[0];
      listQuery.endTime = datePicker[1];
      this.listQuery = listQuery;
      this.getData(0);
      this.getData(1);
    },

    async getData(index) {
      const { domMap, listQuery } = this;
      var myChart = echarts.init(document.getElementById(domMap[index]));
      myChart.showLoading();

      const query = {
        ...listQuery,
        platform: index + 1
      };

      try {
        const { code, data } = await getActiveCollapseListApi(query);
        if (code == 200) {
          const list = {};
          const activeCountArr = [];
          const collapseCountArr = [];
          const dateArr = [];
          const percentArr = [];
          data.forEach((item) => {
            activeCountArr.push(item.activeCount);
            collapseCountArr.push(item.collapseCount);
            dateArr.push(item.date);
            percentArr.push(item.percent);
          });

          list.activeCount = activeCountArr;
          list.collapseCount = collapseCountArr;
          list.percent = percentArr;

          this.list[index] = { ...list, date: dateArr };
          this.upDateEchart(index);
        } else {
          myChart.hideLoading();
        }
      } catch (err) {
        myChart.hideLoading();
      }
    },

    upDateEchart(index) {
      const { domMap, list } = this;
      const currentList = list[index];
      var myChart = echarts.init(document.getElementById(domMap[index]));
      myChart.showLoading();

      const option1 = {
        color: this.$store.state.app.eChartColor,

        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['崩溃数', '总数', '崩溃率']
        },
        grid: {
          left: 200,
          right: 200
        },
        xAxis: [
          {
            type: 'category',
            data: currentList.date,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '崩溃率',
            min: 0,
            max: 100,
            interval: 20,
            axisLabel: {
              formatter: '{value} %'
            }
          },
          {
            type: 'value',
            name: '数量',
            min: 0,
            max: Math.ceil(Math.max(...currentList.activeCount)),
            interval: Math.ceil(Math.max(...currentList.activeCount) / 5),
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '崩溃数',
            type: 'bar',
            yAxisIndex: 1,
            data: currentList.collapseCount
          },
          {
            name: '总数',
            type: 'bar',
            yAxisIndex: 1,
            data: currentList.activeCount
          },
          {
            name: '崩溃率',
            type: 'line',
            yAxisIndex: 0,
            data: currentList.percent
          }
        ]
      };

      myChart.setOption(option1, true);
      myChart.hideLoading();
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  margin: 15px;
  .p-t-15 {
    padding-top: 15px;
  }
  .w-140 {
    width: 140px;
  }
}
</style>
